<template>
  <div>
      <table>
          <thead>
            <tr>
              <td>
                <label >
                   <!-- checked:用于设定勾选状态 -->
                 <input @change="checkAll" type="checkbox" :checked="isCheckAll"/>
                </label>
              </td>
              <td>序号</td>
              <td>商品名</td>
              <td>单价</td>
              <td>数量</td>
              <td>小计</td>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(food,i) in foods" :key="i">
              <td>
                <!-- 推荐单标签闭环，以前版本会报错，如果不闭合 -->
                <input type="checkbox" v-model="food.checked" />
                {{food.checked}}
              </td>
              <td>{{i+1}}</td>
              <td>{{food.name}}</td>
              <td>${{food.price}}</td>
              <td>
                <button @click="food.count--" :disabled="food.count == 1">-</button>
                <span>{{food.count}}</span>
                <button @click="food.count++">+</button>
              </td>
              <td>${{food.price * food.count}}</td>
            </tr>
          </tbody>
          <tfoot>
            <tr>
              <td colspan="6">总价格:${{getTotal}}</td>
            </tr>
          </tfoot>
      </table>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        foods: [
          { name: '茶碗蒸蛋', price: 9, count: 1, checked: true },
          { name: '小笼包', price: 12, count: 4, checked: false },
          { name: '豆腐脑', price: 6, count: 10, checked: true },
          { name: '豆浆', price: 4, count: 1, checked: false },
          { name: '油条', price: 2, count: 7, checked: true },
        ],
      }
    },

// -----------------------------------------------------------

    // 事件触发的方法：methods
    methods: {
      // 如果事件在调用时,没写(),则默认参数1 是事件参数
      checkAll(e) {
        // 查看 checked 属性
        console.log(e.target.checked);
        // 读取全选框的值，赋值给每个商品的checked属性
        this.foods.forEach(
          food => (food.checked = e.target.checked)
        )
      }
    },
// -----------------------------------------------------------
    computed: {
      // 判断是否全选：每一个的checked都是true
      isCheckAll() {
        return this.foods.every(food => food.checked) 
      },
      getTotal(){
        // reduce:让数组元素拼出一个值
        var a = this.foods.reduce((sum,food)=>{
          const {price,count,checked} = food
          // *true 相当于 *1
          // *false 相当于*0
          // 没有勾选，就是 sum+0，既不累加
          return sum+price * count*checked
        },0)
        return a
      }
    },

  }
</script>

<style lang="scss" scoped>
table{
  border-collapse: collapse;
  thead{
    background-color: darkblue;
    color: white;
  }
  td{
    padding: 10px 20px;
    border: 1px solid gray;
    span{
      display: inline-block;
      width: 40px;
      text-align: center;
    }
  }
}
</style>